/*
Java source file
Copyright: Umschalt.com 2012
*/
package com.david.documentation.web.view.panels;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.validator.StringValidator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;

public class CaptchaPanel extends Panel{


	private TextField<String> inputField;

	public CaptchaPanel(String id, final String link) {
		super(id);

		Document document = null;
		String hiddenField = "";
		Element imageElement = null;

		try {
			document = Jsoup.connect(link).ignoreContentType(true).get();
			Jsoup.connect(link).post();
			org.jsoup.select.Elements elements = document.select("form");

			for (Element elem : elements){
				if (elem.attr("name").equals("INPF")){
					imageElement = elem.select("img").get(0);
					imageElement.attr("src", "http://download.serienjunkies.org" + imageElement.select("img").get(0).attr("src"));
					hiddenField = elem.select("input[type=hidden]").get(0).attr("value");
					break;
				}
			}
			// wenn imageelement == null dann müsste captcha schon richtig -> jdownloader bild

		} catch (Exception e) {
			e.printStackTrace();
		}

		final Label captchaImage = new Label("captchaImage",imageElement != null ? imageElement.outerHtml() : "FEHLER");
		captchaImage.setEscapeModelStrings(false).setOutputMarkupId(true);
		add(captchaImage);

		/* Captcha Form */
		final Form form = new Form("form");
		inputField = new TextField<String>("input",new Model<String>(""));
		inputField.setRequired(true).setOutputMarkupId(true);
		inputField.add(StringValidator.minimumLength(3));
		inputField.setVisible(imageElement != null);
		form.add(inputField);
		add(form);

		/* Download Form */
		final Form downloadForm = new Form("downloadform");
		downloadForm.add(new SimpleAttributeModifier("action","http://127.0.0.1:9666/flash/addcrypted2"));
		downloadForm.add(new SimpleAttributeModifier("name","cnlform"));
		downloadForm.add(new SimpleAttributeModifier("target","hidden"));
		downloadForm.add(new SimpleAttributeModifier("method","POST"));
		downloadForm.setOutputMarkupId(true);
		final HiddenField<String> source = new HiddenField<String>("source",new Model<String>(""));
		final HiddenField<String> jk = new HiddenField<String>("jk",new Model<String>(""));
		final HiddenField<String> crypted = new HiddenField<String>("crypted",new Model<String>(""));
		source.setOutputMarkupId(true);
		crypted.setOutputMarkupId(true);
		jk.setOutputMarkupId(true);
		downloadForm.add(source,jk,crypted);
		add(downloadForm);

		final AjaxLink downloadLink = new AjaxLink("downloadLink") {
			@Override
			public void onClick(AjaxRequestTarget target) {
				target.appendJavascript("$('#"+downloadForm.getMarkupId()+"').submit();");
				// feedback ausgeben
				info("Download wurde mit JDonloader geöffnet");
				target.addChildren(getPage(), FeedbackPanel.class);
			}
		};
		downloadLink.setOutputMarkupId(true);
		add(downloadLink);

		final String finalHiddenField = hiddenField;
		final AjaxSubmitLink sendLink = new AjaxSubmitLink("sendLink",form) {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				try {
					// sende daten an captchaform
					Document doc = Jsoup.connect(link).data("s",finalHiddenField,"c",inputField.getDefaultModelObjectAsString()).post();

					if (doc != null && doc.select("form[name=cnlform]").size() > 0){
						// Captcha richtig
						String sourceValue = doc.select("form[name=cnlform] input[name=source]").get(0).attr("value");
						String cryptedValue = doc.select("form[name=cnlform] input[name=crypted]").get(0).attr("value");
						String jkValue = doc.select("form[name=cnlform] input[name=jk]").get(0).attr("value");

						target.appendJavascript("$('#"+source.getMarkupId()+"').attr('value','"+sourceValue+"')");
						target.appendJavascript("$('#"+crypted.getMarkupId()+"').attr('value','"+cryptedValue+"')");
						target.appendJavascript("$('#"+jk.getMarkupId()+"').attr('value','"+ StringEscapeUtils.escapeJavaScript(jkValue)+"')");

						// Jdownloader starten
						target.appendJavascript("$('#"+downloadLink.getMarkupId()+"').show();");
						target.appendJavascript("$('#"+captchaImage.getMarkupId()+"').hide();");
						target.appendJavascript("$('#"+this.getMarkupId()+"').hide();");
						target.appendJavascript("$('#"+inputField.getMarkupId()+"').hide();");
						target.appendJavascript("$('#"+downloadForm.getMarkupId()+"').submit();");

					}
					else {
						// Captcha Falsch -> neu laden
						target.appendJavascript("$('#"+source.getMarkupId()+"').parents('li').find('a.refresh').click();");
					}
				} catch (IOException e) {
					target.appendJavascript("$('#" + source.getMarkupId() + "').parents('li').find('a.refresh').click();");
					e.printStackTrace();
				}
			}
		};
		sendLink.setOutputMarkupId(true);
		sendLink.setVisible(imageElement != null);
		add(sendLink);
	}
}
